package com.iwhalecloud.bss.kite.cucc.web.controller.scene;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.cart.client.api.cart.query.IQueryKiteShoppingCartService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.shoppingcart.ShoppingCartGroupInstDTO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.*;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IOrderSignService;
import com.iwhalecloud.bss.kite.cucc.client.api.rule.check.ICuccCheckService;
import com.iwhalecloud.bss.kite.cucc.client.api.scene.ICuccSceneService;
import com.iwhalecloud.bss.kite.cucc.client.api.scene.ISceneCommitService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.*;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalInfConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.even.BeforeSceneCommitEvent;
import com.iwhalecloud.bss.kite.cucc.service.even.BeforeSceneReCommitEvent;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosServiceHandler;
import com.iwhalecloud.bss.kite.cucc.web.controller.reception.LocalCustReceptionController;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.util.RuleParamUtils;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.bo.UserInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.rul.core.client.dto.common.RuleCommonParam;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import edu.emory.mathcs.backport.java.util.Arrays;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 场景提交转单
 *
 * @author zou.qinghua
 */
@RestController("cuccSceneCommit")
@RequestMapping("/cuccSceneCommit")
@Api(tags = {"/cuccSceneCommit - 场景提交转单"
})
public class SceneCommitController {

    private static final ZLogger LOGGER = ZLoggerFactory.getLogger(SceneCommitController.class, KeyConsts.LOG_MODULE);

    @Autowired
    private ISceneCommitService sceneCommitService;

    @Autowired
    private IOrderSignService orderSignService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Resource
    private ApplicationContext applicationContext;

    @Autowired
    private IInfServiceBus infServiceBus;

    @Autowired
    private ICuccCheckService iCuccCheckService;

    @Autowired
    private ICuccSceneService cuccSceneService;

    @Autowired
    private IQueryKiteShoppingCartService queryKiteShoppingCartService;

    @Autowired
    private IInfServiceBus infService;

    @SuppressWarnings("deprecation")
    @KiteTransactional
    @ApiOperation(value = "场景提交转单", notes = "场景提交转单，返回转单结果")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "templateId", value = "模板", required = false),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例标识", required = false)
    })
    @PostMapping("/commit")
    public DataResult<String> commitScene(String templateId, String sceneInstId) {
        try {
            /*SceneTemplate sceneTemplate = SceneTemplateCache.get(templateId);
            List<SceneModule> sceneModuleList =  sceneTemplate.getSceneModules();
            Boolean checkAccountModule = sceneModuleList.stream().anyMatch(sceneModule -> {
                return LocalKeyConsts.ACCOUNT_MODULE_ID.equals(sceneModule.getKiteModule().getModuleId());
            });
            Boolean checkContractModule = sceneModuleList.stream().anyMatch(sceneModule -> {
                return LocalKeyConsts.CONTRACT_MODULE_ID.equals(sceneModule.getKiteModule().getModuleId());
            });*/
            Boolean checkAccountModule = false;
            Boolean checkContractModule = false;
            if (!KiteStringUtils.isEmpty(sceneInstId)) {
                KiteWebContext.getContext().setCurrentSceneInstId(sceneInstId);
            }
            String currentSceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
            String loadingTariffPlanFlag = querySceneInstService.getExtParameterValue(currentSceneInstId, "loadingTariffPlanFlag");
            if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_T)) {
                return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端仍在还原场景信息，请稍候...");
            }
            else if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_F)) {
                return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端异步处理场景信息失败，请重新进入页面...");
            }
            String renderOrderType = querySceneInstService.getExtParameterValue(currentSceneInstId, "renderOrderType");
            if(KiteStringUtils.isEqual(renderOrderType, "orderRejection")) {
                // app甩单补录提交，调用工单完成接口，走重提方法
                DataResult<String> dataResult = this.recommitScene(currentSceneInstId, "DEAL_SUCCESS");
                if(KiteStringUtils.isEqual(dataResult.getResultCode(), "0")) {
                    String rejectionOrderId = querySceneInstService.getExtParameterValue(currentSceneInstId, "rejectionOrderId");
                    dataResult.setResultObject("提交成功，订单编号：" + rejectionOrderId);
                }
                return dataResult;
            }

            String custId = KiteWebContext.getContext().getCustId();
            LoginInfo loginInfo = ContextUtil.getLoginInfo();
            String staffId = loginInfo.getUserInfo().getUserId().toString();
            String serviceOfferId = querySceneInstService.getSceneInst(currentSceneInstId).getServiceOfferId();
            BeforeSceneCommitEvent beforeSceneCommitEvent = new BeforeSceneCommitEvent(this, custId, staffId,
                currentSceneInstId, serviceOfferId);
            applicationContext.publishEvent(beforeSceneCommitEvent);

            DataResult result = sceneCommitService
                .commitScene(currentSceneInstId, staffId, loginInfo.getOrgInfo().getOrgId().toString(),
                    (CuccContextCustDTO) KiteWebContext.getContext().getCust(), checkAccountModule,
                    checkContractModule);
            StringBuilder commitResultStr = new StringBuilder();
            commitResultStr.append("提交成功，订单编号：").append(result.getResultObject());
            DataResult commitResult = ErrorConsts.SUCCESS.getResult(commitResultStr.toString());
            commitResult.setResultMsg(result.getResultMsg());

            /* 两个接口合并为一个接口，订单归集接口order.attrs节点新增参数worksheetID，用于关闭代办
            if(KiteStringUtils.isEqual(result.getResultCode(), "0")) {
                // 落地方补录，提交成功后，再调工单完成接口关闭补录代办
                if(KiteStringUtils.isEqual(renderOrderType, "orderFallPlace")) {
                    Map<String, Object> sceneExtParams = this.querySceneInstService.getExtParameter(currentSceneInstId);
                    String worksheetId = MapUtils.getString(sceneExtParams, "fallPlaceFlowId");
                    String taskId = MapUtils.getString(sceneExtParams, "fallPlaceTaskId");
                    String taskCode = MapUtils.getString(sceneExtParams, "fallPlaceTaskCode");
                    String sessionId = ContextUtil.getHttpSessoinId();
                    CompletableFuture.runAsync(() -> {
                        try {
                            ContextUtil.setHttpSessoinId(sessionId);
                            infService.endWorkSheetTask(worksheetId, taskCode, taskId, "ORDER_START_RENT", staffId, null, null);
                        } catch (Exception e) {
                            logger.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), e, ErrorConsts.SYSTEM_ERROR.getMsg());
                        }
                    });
                }
            }*/

            return commitResult;
        }
        catch (BssException ex) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult(ex.getFailCode(), ex.getFailMsg());
        }
    }

    @SuppressWarnings({
        "deprecation", "unchecked"
    })
    @KiteTransactional
    @ApiOperation(value = "场景批量提交转单", notes = "场景批量提交转单，返回转单结果")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "templateId", value = "模板", required = false),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例标识，多个用逗号隔开", required = true)
    })
    @PostMapping("/commitBatch")
    public DataResult<List<String>> commitSceneBatch(String templateId, String sceneInstId) {
        try {
            String cartId = this.cuccSceneService.getCartIdFromES().getResultObject();
            DataResult<String> resultData = new DataResult<String>();
            List<String> orderIds = new ArrayList<>();
            List<String> sceneInstIds = Arrays.asList(sceneInstId.split(","));
            for (String sceneInstIdStr : sceneInstIds) {
                ShoppingCartGroupInstDTO shoppingCartGroupInstDTO = queryKiteShoppingCartService.getShoppingCartGroupInstByGroupId(sceneInstIdStr, cartId).getResultObject();
                SpringUtil.getBean(LocalCustReceptionController.class).initContext(shoppingCartGroupInstDTO.getCustId(), "0");

                Boolean checkAccountModule = false;
                Boolean checkContractModule = false;
                KiteWebContext.getContext().setCurrentSceneInstId(sceneInstIdStr);

                String custId = KiteWebContext.getContext().getCustId();
                String staffId = ContextUtil.getUserId().toString();
                String currentSceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
                String serviceOfferId = querySceneInstService.getSceneInst(currentSceneInstId).getServiceOfferId();

                BeforeSceneCommitEvent beforeSceneCommitEvent = new BeforeSceneCommitEvent(this, custId, staffId,
                    currentSceneInstId, serviceOfferId);
                applicationContext.publishEvent(beforeSceneCommitEvent);

                resultData = sceneCommitService
                    .commitScene(currentSceneInstId, staffId, ContextUtil.getLoginInfo().getOrgInfo().getOrgId().toString(),
                        (CuccContextCustDTO) KiteWebContext.getContext().getCust(), checkAccountModule,
                        checkContractModule);
                orderIds.add(resultData.getResultObject());
            }

            List<String> results = new ArrayList<>();
            StringBuilder commitResult = new StringBuilder();
            commitResult.append("订单提交成功，业务订单号：").append(KiteStringUtils.join(orderIds, ","));
            results.add(commitResult.toString());

            DataResult<List<String>> result = ErrorConsts.SUCCESS.getResult(results);
            result.setResultMsg(resultData.getResultMsg());
            return result;
        }
        catch (BssException ex) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut(ex.getFailCode(), ex.getFailMsg());
        }
        return null;
    }

    @SuppressWarnings("deprecation")
    @KiteTransactional
    @ApiOperation(value = "订单重提", notes = "重提，用于打回重提和异常重提场景")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例标识", required = false),
        @ApiImplicitParam(name = "dealResult", value = "处理结果", required = false)
    })
    @PostMapping("/recommit")
    public DataResult<String> recommitScene(String sceneInstId, String dealResult) {
        try {
            /*SceneTemplate sceneTemplate = SceneTemplateCache.get(templateId);
            List<SceneModule> sceneModuleList =  sceneTemplate.getSceneModules();
            Boolean checkAccountModule = sceneModuleList.stream().anyMatch(sceneModule -> {
                return LocalKeyConsts.ACCOUNT_MODULE_ID.equals(sceneModule.getKiteModule().getModuleId());
            });
            Boolean checkContractModule = sceneModuleList.stream().anyMatch(sceneModule -> {
                return LocalKeyConsts.CONTRACT_MODULE_ID.equals(sceneModule.getKiteModule().getModuleId());
            });*/
            /*KiteSceneInst kiteSceneInst = this.querySceneInstService
                .getSceneInst(sceneInstId, KiteWebContext.getContext().getCustId());
            kiteSceneInst.setOperType("1008"); //业务变更
            this.operateSceneInstService.createSceneInst(kiteSceneInst);*/
            String loadingTariffPlanFlag = querySceneInstService.getExtParameterValue(sceneInstId, "loadingTariffPlanFlag");
            if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_T)) {
                return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端仍在还原场景信息，请稍候...");
            }
            else if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_F)) {
                return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端异步处理场景信息失败，请重新进入页面...");
            }
            // 【专线】商品超时起租校验埋点
            String custId = KiteWebContext.getContext().getCustId();
            RuleCommonParam ruleCommonParam = RuleParamUtils.getRuleParam(custId);
            iCuccCheckService.specialLineStartRentCheck(sceneInstId, ruleCommonParam);

            CuccContextCustDTO custDto = (CuccContextCustDTO) KiteWebContext.getContext().getCust();
            if (!KiteStringUtils.isEmpty(sceneInstId)) {
                KiteWebContext.getContext().setCurrentSceneInstId(sceneInstId);
            }
            LoginInfo loginInfo = ContextUtil.getLoginInfo();
            UserInfo userInfo = loginInfo.getUserInfo();
            String staffId = KiteMapUtils.getStrValue(userInfo.getExtParams(), "accountId");
            if (KiteStringUtils.isEmpty(userInfo.getUserCode())) {
                staffId = userInfo.getUserId().toString();
            }
            String serviceOfferId = querySceneInstService.getSceneInst(sceneInstId).getServiceOfferId();

            String rootInstId = this.querySceneInstService.getSceneInst(sceneInstId).getRootInstId();
            InstType instType = this.querySceneInstService.getSceneInst(sceneInstId).getRootInstType();
            KiteInst kiteInst = this.querySceneInstService.getKiteInst(custDto.getCustId(), instType, rootInstId);
            String cateId = OfferCache.get(kiteInst.getSpecId()).getCateId();
            String extTips = DcPublicCache.getCodea("20201218001", cateId);

            String worksheetId = querySceneInstService.getExtParameterValue(sceneInstId, "worksheetId");
            String taskCode = querySceneInstService.getExtParameterValue(sceneInstId, "taskCode");
            String taskId = querySceneInstService.getExtParameterValue(sceneInstId, "taskId");

            BeforeSceneReCommitEvent beforeSceneCommitEvent = new BeforeSceneReCommitEvent(this, custId, staffId,
                sceneInstId, serviceOfferId);
            applicationContext.publishEvent(beforeSceneCommitEvent);

            // app订购甩单补录、资源核查甩单补录，dealResult 传 DEAL_SUCCESS
            String renderOrderType = querySceneInstService.getExtParameterValue(sceneInstId, "renderOrderType");
            if(KiteStringUtils.isEqual(renderOrderType, "orderRejection")) {
                dealResult = "DEAL_SUCCESS";
            }

            DataResult result = orderSignService.overOrderTask(sceneInstId, staffId,
                loginInfo.getOrgInfo().getOrgId().toString(), worksheetId, taskCode, taskId,
                dealResult, null, true, true, custDto);
            if (!KiteStringUtils.isEmpty(extTips) && !KiteStringUtils.equals((String) result.getResultObject(), "-1")) {
                result.setResultMsg(extTips);
            }
            return result;
        }
        catch (BssException ex) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult(ex.getFailCode(), ex.getFailMsg());
        }
    }

    @KiteTransactional
    @ApiOperation(value = "订单修改提交", notes = "订单修改提交")
    @PostMapping("/commitModifyScene")
    public DataResult<String> commitModifyScene(String sceneInstId) {
        try {
            if (!KiteStringUtils.isEmpty(sceneInstId)) {
                KiteWebContext.getContext().setCurrentSceneInstId(sceneInstId);
            }

            String staffId = ContextUtil.getUserId().toString();
            String currentSceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();

//            BeforeSceneCommitEvent beforeSceneCommitEvent = new BeforeSceneCommitEvent(this, custId, staffId,
//                currentSceneInstId, serviceOfferId);
//            applicationContext.publishEvent(beforeSceneCommitEvent);
            IKitePosServiceHandler posServiceHandler = SpringUtil.getBean(IKitePosServiceHandler.class);
            KitePosDTO posDto = posServiceHandler.deal(sceneInstId, staffId, ContextUtil.getLoginInfo().getOrgInfo().getOrgId().toString(), (CuccContextCustDTO) KiteWebContext.getContext().getCust(), false, false, null);
            /* 订单中心配套改造,归集后的转单报文中实例ID不替换为订单中心的ID
            //替换goods节点的InstanceId为订单中心返回的值
            CuccPosServiceUtils.replaceGoodsInstanceId(sceneInstId, posDto);
            */
            return sceneCommitService
                .commitModifyScene(currentSceneInstId, staffId,
                    ContextUtil.getLoginInfo().getOrgInfo().getOrgId().toString(),
                    (CuccContextCustDTO) KiteWebContext.getContext().getCust(), posDto);
        }
        catch (BssException ex) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult(ex.getFailCode(), ex.getFailMsg());
        }
    }

    @KiteTransactional
    @ApiOperation(value = "追单", notes = "用于追单场景")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例标识")
    })
    @PostMapping("/chaseOrder")
    public DataResult<String> chaseOrder(String sceneInstId) {
        StringBuilder result = new StringBuilder();
        if (!KiteStringUtils.isEmpty(sceneInstId)) {
            KiteWebContext.getContext().setCurrentSceneInstId(sceneInstId);
        }
        String loadingTariffPlanFlag = querySceneInstService.getExtParameterValue(sceneInstId, "loadingTariffPlanFlag");
        if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_T)) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端仍在还原场景信息，请稍候...");
        }
        else if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_F)) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端异步处理场景信息失败，请重新进入页面...");
        }
        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        String custId = KiteWebContext.getContext().getCustId();
        UserInfo userInfo = loginInfo.getUserInfo();
        String staffId = KiteMapUtils.getStrValue(userInfo.getExtParams(), "accountId");
        if (KiteStringUtils.isEmpty(userInfo.getUserCode())) {
            staffId = userInfo.getUserId().toString();
        }
        String serviceOfferId = querySceneInstService.getSceneInst(sceneInstId).getServiceOfferId();
        BeforeSceneCommitEvent beforeSceneCommitEvent = new BeforeSceneCommitEvent(this, custId, staffId, sceneInstId,
            serviceOfferId);
        applicationContext.publishEvent(beforeSceneCommitEvent);
        IKitePosServiceHandler kitePosServiceHandler = SpringUtil.getBean(IKitePosServiceHandler.class);
        KitePosDTO kitePosDTO = kitePosServiceHandler.deal(sceneInstId, loginInfo.getUserInfo().getUserId().toString(),
            loginInfo.getOrgInfo().getOrgId().toString(),
            (CuccContextCustDTO) KiteWebContext.getContext().getCust(), false, false, null);
        //替换goods节点的InstanceId为订单中心返回的值
        //CuccPosServiceUtils.replaceGoodsInstanceId(sceneInstId, kitePosDTO);
        Map<String, Object> businessData = KiteMapUtils.beanToMap(kitePosDTO);
        //追单报文的request和account节点需要特殊处理,customer节点在handler中做处理
        KitePosRequestDTO requestDTO = (KitePosRequestDTO) businessData.get("request");
        String dateStr = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14);
        String code = RandomStringUtils.randomNumeric(12);
        requestDTO.setSerialNo(dateStr.concat(code));
        //isNewCustomer为整型
        KitePosCustomerDTO customerDTO = (KitePosCustomerDTO) businessData.get("customer");
        Map customerMap = KiteMapUtils.beanToMap(customerDTO);
        String isNewCustomer = KiteMapUtils.getString(customerMap, "isNewCustomer");
        customerMap.put("isNewCustomer", Integer.parseInt(isNewCustomer));
        businessData.put("customer", customerMap);
        //attachments节点不传uploadTime
        KitePosOrderDTO order = (KitePosOrderDTO) businessData.get("order");
        List<KitePosAttachmentDTO> attachments = order.getAttachments();
        if (KiteListUtils.isNotEmpty(attachments)) {
            List<KitePosAttachmentDTO> targetList = new ArrayList<>();
            attachments.forEach(attachment -> {
                KitePosAttachmentDTO target = new KitePosAttachmentDTO();
                KiteBeanUtils.copyProperties(attachment, target, "uploadTime");
                targetList.add(target);
            });
            order.setAttachments(targetList);
        }
        businessData.put("order", order);
        String orderId = querySceneInstService.getExtParameterValue(sceneInstId, "sourceOrderId");

        Map<String, Object> respMap = infServiceBus.specialProcess("ALTER", orderId, null, businessData);
        Map<String, Object> uniBssHead = KiteMapUtils.getValue(respMap, "UNI_BSS_HEAD");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(uniBssHead, "RESP_CODE"), LocalInfConsts.RESP_SUCCESS)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(uniBssHead, "RESP_CODE"), KiteMapUtils.getString(uniBssHead, "RESP_DESC"));
        }
        Map<String, Object> uniBssBody = KiteMapUtils.getValue(respMap, "UNI_BSS_BODY");
        Map<String, Object> specialProcessRsp = KiteMapUtils.getValue(uniBssBody, "SPECIAL_PROCESS_RSP");
        if (KeyConsts.SUCCESS_0.equals(KiteMapUtils.getString(specialProcessRsp, "status"))) {
            result.append("订单提交成功");
        }
        else {
            return ErrorConsts.INF_INVOKE_EXCEPTION.getResult(null, KiteMapUtils.getString(specialProcessRsp, "message"));
        }
        return ErrorConsts.SUCCESS.getResult(result.toString());
    }

    @KiteTransactional
    @ApiOperation(value = "退单", notes = "用于退单场景")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "工单号", required = true),
        @ApiImplicitParam(name = "cancelReason", value = "退单原因", required = true)
    })
    @PostMapping("/cancelOrder")
    public DataResult<String> cacelOrder(String orderId, String cancelReason) {

        String sceneInstId = KiteWebContext.getContextNew().getCurrentSceneInstId();
        String loadingTariffPlanFlag = querySceneInstService.getExtParameterValue(sceneInstId, "loadingTariffPlanFlag");
        if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_T)) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端仍在还原场景信息，请稍候...");
        }
        else if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_F)) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端异步处理场景信息失败，请重新进入页面...");
        }
        if (KiteStringUtils.isEmpty(cancelReason)) {
            KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10023");
            if (Objects.nonNull(kiteAttr)) {
                cancelReason = kiteAttr.getValue();
            }
        }
        Map<String, Object> flowProcessDataMap = new HashMap<>();
        flowProcessDataMap.put("ORD10023", cancelReason);

        // 退单附件信息
        String AttachementStr = dealAttachements(sceneInstId);
        if(KiteStringUtils.isNotEmpty(AttachementStr)){
            JSONArray orderAttachArr = JSONArray.parseArray(AttachementStr);
            Map dataMap = new HashMap<>();
            dataMap.put("orderAttachArr",orderAttachArr);
            flowProcessDataMap.put("ORD10021", dataMap);
        }

        //退单备注描述
        KiteAttr noteAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10022");
        if (Objects.nonNull(noteAttr)) {
            flowProcessDataMap.put("ORD10022", noteAttr.getValue());
        }

        LoginInfo loginInfo = ContextUtil.getLoginInfo();

        IKitePosServiceHandler kitePosServiceHandler = SpringUtil.getBean(IKitePosServiceHandler.class);
        KitePosDTO kitePosDTO = kitePosServiceHandler.deal(sceneInstId,
            loginInfo.getUserInfo().getUserId().toString(), loginInfo.getOrgInfo().getOrgId().toString(),
            (CuccContextCustDTO) KiteWebContext.getContext().getCust(), false, false, "CANCEL");
        //替换goods节点的InstanceId为订单中心返回的值
        CuccPosServiceUtils.replaceGoodsInstanceId(sceneInstId, kitePosDTO);
        Map<String, Object> tempBusinessData = new HashMap<>();
        List<KitePosGoodsDTO> goods = kitePosDTO.getGoods();
        List<Map<String, Object>> goodsList = new ArrayList<>();
        if (KiteListUtils.isNotEmpty(goods)) {
            goods.forEach(good -> {
                Map<String, Object> goodMap = new HashMap<>();
                goodMap.put("count", good.getCount());
                goodMap.put("code", good.getCode());
                goodMap.put("instanceId", good.getInstanceId());
                goodsList.add(goodMap);
            });
            tempBusinessData.put("goods", goodsList);
        }
        Map<String, Object> order = new HashMap<>();
        order.put("status", "4"); // 关闭状态
        tempBusinessData.put("order", order);

        Map<String, Object> respMap = infServiceBus.specialProcess("CANCEL", orderId, flowProcessDataMap, tempBusinessData);
        Map<String, Object> uniBssHead = KiteMapUtils.getValue(respMap, "UNI_BSS_HEAD");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(uniBssHead, "RESP_CODE"), LocalInfConsts.RESP_SUCCESS)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(uniBssHead, "RESP_CODE"),
                KiteMapUtils.getString(uniBssHead, "RESP_DESC"));
        }
        Map<String, Object> uniBssBodyRespMap = KiteMapUtils.getValue(respMap, "UNI_BSS_BODY");
        Map<String, Object> specialProcessRspMap = KiteMapUtils.getValue(uniBssBodyRespMap, "SPECIAL_PROCESS_RSP");
        if (!LocalInfConsts.UNI_BSS_BODY_RESULT_SUCCESS.equals(KiteMapUtils.getString(specialProcessRspMap, "status"))) {
            return ErrorConsts.INF_INVOKE_EXCEPTION.getResult(KiteMapUtils.getString(specialProcessRspMap, "status"),
                KiteMapUtils.getString(specialProcessRspMap, "message"));
        }
        return ErrorConsts.SUCCESS.getResult("订单退单成功");
    }

    @KiteTransactional
    @ApiOperation(value = "挂起、解挂", notes = "用于挂起或解挂场景")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "工单号", required = true),
        @ApiImplicitParam(name = "cancelReason", value = "退单原因", required = true),
        @ApiImplicitParam(name = "opType", value = "操作类型", required = true),
    })
    @PostMapping("/lockOrReleaseOrder")
    public DataResult<String> lockOrReleaseOrder(String orderId, String reason, String opType) {
        String sceneInstId = KiteWebContext.getContextNew().getCurrentSceneInstId();
        String loadingTariffPlanFlag = querySceneInstService.getExtParameterValue(sceneInstId, "loadingTariffPlanFlag");
        if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_T)) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端仍在还原场景信息，请稍候...");
        }
        else if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_F)) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端异步处理场景信息失败，请重新进入页面...");
        }
        if (KiteStringUtils.isEmpty(reason)) {
            KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10020");
            if (Objects.nonNull(kiteAttr)) {
                reason = kiteAttr.getValue();
            }
        }
        Map<String, Object> flowProcessDataMap = new HashMap<>();
        flowProcessDataMap.put("ORD10020", reason);

        LoginInfo loginInfo = ContextUtil.getLoginInfo();

        IKitePosServiceHandler kitePosServiceHandler = SpringUtil.getBean(IKitePosServiceHandler.class);
        KitePosDTO kitePosDTO = kitePosServiceHandler.deal(sceneInstId,
            loginInfo.getUserInfo().getUserId().toString(), loginInfo.getOrgInfo().getOrgId().toString(),
            (CuccContextCustDTO) KiteWebContext.getContext().getCust(), false, false, null);
        //替换goods节点的InstanceId为订单中心返回的值
        CuccPosServiceUtils.replaceGoodsInstanceId(sceneInstId, kitePosDTO);
        Map<String, Object> tempBusinessData = new HashMap<>();
        List<KitePosGoodsDTO> goods = kitePosDTO.getGoods();
        List<Map<String, Object>> goodsList = new ArrayList<>();
        String startDate = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14);
        if (KiteListUtils.isNotEmpty(goods) && "RELEASE".equals(opType)) {
            goods.forEach(good -> {
                Map<String, Object> goodMap = new HashMap<>();
                goodMap.put("count", good.getCount());
                goodMap.put("code", good.getCode());
                goodMap.put("instanceId", good.getInstanceId());
                List<KitePosProductDTO> productDTOList = good.getProducts();
                List<Map<String, Object>> products = new ArrayList<>();
                if (KiteListUtils.isNotEmpty(productDTOList)) {
                    productDTOList.forEach(productDTO -> {
                        Map<String, Object> product = new HashMap<>();
                        product.put("instanceId", productDTO.getInstanceId());
/*20220222版本将AZ要求完成时间移至order节点下*/
//                            product.put("attrs", attrAZ(sceneInstId));
                        products.add(product);
                    });
                }
                if (KiteListUtils.isNotEmpty(products)) {
                    goodMap.put("products", products);
                }
                goodsList.add(goodMap);
            });
            tempBusinessData.put("goods", goodsList);
        }
        Map<String, Object> order = new HashMap<>();
        if ("LOCK".equals(opType)) {
            order.put("status", "5"); // 状态
            // 挂起时限
            KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10279");
            if (Objects.nonNull(kiteAttr) && !KiteStringUtils.isEmpty(kiteAttr.getValue())) {
                List<KitePosAttrDTO> attrs = new ArrayList<>();
                KitePosAttrDTO attr = new KitePosAttrDTO();
                attr.setCode("ORD10279");
                attr.setType("STRING");
                attr.setStartDate(startDate);
                attr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                attr.setValue(kiteAttr.getValue());
                attrs.add(attr);
                order.put("attrs", attrs);
            }
        }
        if ("RELEASE".equals(opType)) {
            order.put("status", "0"); // 状态
            // 全程要求完成时间
            KiteAttr allFinishAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10012");
            List<KiteAttr> attrLists = new ArrayList<>();
            // 全程要求完成时间更改了属性类型 对值进行截取
            if (Objects.nonNull(allFinishAttr) && KiteStringUtils.isNotEmpty(allFinishAttr.getValue())) {
                allFinishAttr.setValue(allFinishAttr.getValue().substring(0, 10));
                allFinishAttr.setValueDesc(allFinishAttr.getValue().substring(0, 10));
                attrLists.add(allFinishAttr);
            }
            if (KiteListUtils.isNotEmpty(attrLists)) {
                List<KitePosAttrDTO> attrs = new ArrayList<>();
                attrLists.forEach(attrList -> {
                    KitePosAttrDTO attr = new KitePosAttrDTO();
                    attr.setCode(attrList.getFieldName());
                    attr.setType("STRING");
                    attr.setStartDate(startDate);
                    attr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                    attr.setValue(attrList.getValue());
                    attrs.add(attr);
                });
                attrs.addAll(attrAZ(sceneInstId));
                order.put("attrs", attrs);
            }
        }
        tempBusinessData.put("order", order);

        Map<String, Object> respMap = infServiceBus.specialProcess(opType, orderId, flowProcessDataMap, tempBusinessData);
        Map<String, Object> uniBssHead = KiteMapUtils.getValue(respMap, "UNI_BSS_HEAD");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(uniBssHead, "RESP_CODE"), LocalInfConsts.RESP_SUCCESS)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(uniBssHead, "RESP_CODE"),
                KiteMapUtils.getString(uniBssHead, "RESP_DESC"));
        }
        Map<String, Object> uniBssBodyRespMap = KiteMapUtils.getValue(respMap, "UNI_BSS_BODY");
        Map<String, Object> specialProcessRspMap = KiteMapUtils.getValue(uniBssBodyRespMap, "SPECIAL_PROCESS_RSP");
        if (!LocalInfConsts.UNI_BSS_BODY_RESULT_SUCCESS.equals(KiteMapUtils.getString(specialProcessRspMap, "status"))) {
            return ErrorConsts.INF_INVOKE_EXCEPTION.getResult(KiteMapUtils.getString(specialProcessRspMap, "status"),
                KiteMapUtils.getString(specialProcessRspMap, "message"));
        }
        return ErrorConsts.SUCCESS.getResult("操作订单成功");
    }

    @KiteTransactional
    @ApiOperation(value = "加急、延期", notes = "用于加急或延期场景")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderId", value = "工单号", required = true),
        @ApiImplicitParam(name = "opType", value = "操作类型", required = true),
    })
    @PostMapping("/urgentOrPostpone")
    public DataResult<String> urgentOrPostpone(String orderId, String opType) {

        Map<String, Object> flowProcessDataMap = new HashMap<>();

        String sceneInstId = KiteWebContext.getContextNew().getCurrentSceneInstId();
        IKitePosServiceHandler kitePosServiceHandler = SpringUtil.getBean(IKitePosServiceHandler.class);

        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        String loadingTariffPlanFlag = querySceneInstService.getExtParameterValue(sceneInstId, "loadingTariffPlanFlag");
        if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_T)) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端仍在还原场景信息，请稍候...");
        }
        else if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_F)) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端异步处理场景信息失败，请重新进入页面...");
        }
        //数据准备
        KitePosDTO kitePosDTO = kitePosServiceHandler.deal(sceneInstId,
            loginInfo.getUserInfo().getUserId().toString(), loginInfo.getOrgInfo().getOrgId().toString(),
            (CuccContextCustDTO) KiteWebContext.getContext().getCust(), false, false, null);
        //A、Z端全程要求完成时间
        KiteAttr aCommAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.REPLACE_A);
        KiteAttr zCommAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.REPLACE_Z);
        //属性起始时间
        String startDate = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14);
        //替换goods节点的InstanceId为订单中心返回的值
        CuccPosServiceUtils.replaceGoodsInstanceId(sceneInstId, kitePosDTO);
        Map<String, Object> tempBusinessData = new HashMap<>();
        List<KitePosGoodsDTO> goods = kitePosDTO.getGoods();
        List<Map<String, Object>> goodsList = new ArrayList<>();
        if (KiteListUtils.isNotEmpty(goods)) {
            goods.forEach(good -> {
                Map<String, Object> goodMap = new HashMap<>();
                goodMap.put("count", good.getCount());
                goodMap.put("code", good.getCode());
                goodMap.put("instanceId", good.getInstanceId());
                List<KitePosProductDTO> productDTOList = good.getProducts();
                List<Map<String, Object>> products = new ArrayList<>();
                if (KiteListUtils.isNotEmpty(productDTOList)) {
                    productDTOList.forEach(productDTO -> {
                        Map<String, Object> product = new HashMap<>();
                        product.put("instanceId", productDTO.getInstanceId());
                        /*20220222版本将AZ要求完成时间移至order节点下*/
//                        product.put("attrs", attrAZ(sceneInstId));
                        products.add(product);
                    });
                }
                if (KiteListUtils.isNotEmpty(products)) {
                    goodMap.put("products", products);
                }
                goodsList.add(goodMap);
            });
            tempBusinessData.put("goods", goodsList);
        }
        Map<String, Object> order = new HashMap<>();
        KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10012");
        //预约时间
        KiteAttr appointTimeAttr = querySceneInstService.getCommonAttr(sceneInstId, "ORD10283");
        List<KitePosAttrDTO> orderAttrs = new ArrayList<>();
        if (Objects.nonNull(kiteAttr) && !KiteStringUtils.isEmpty(kiteAttr.getValue())) {
            KitePosAttrDTO attr = new KitePosAttrDTO();
            attr.setCode("ORD10012");
            attr.setType("STRING");
            attr.setStartDate(startDate);
            attr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
            attr.setValue(kiteAttr.getValue());
            orderAttrs.add(attr);
        }
        if (Objects.nonNull(appointTimeAttr) && KiteStringUtils.isNotEmpty(appointTimeAttr.getValue())) {
            KitePosAttrDTO attr = new KitePosAttrDTO();
            attr.setCode("ORD10283");
            attr.setType("STRING");
            attr.setStartDate(startDate);
            attr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
            attr.setValue(appointTimeAttr.getValue());
            orderAttrs.add(attr);
        }
        orderAttrs.addAll(attrAZ(sceneInstId));
        order.put("attrs", orderAttrs);
        tempBusinessData.put("order", order);

        Map<String, Object> respMap = infServiceBus.specialProcess(opType, orderId, flowProcessDataMap, tempBusinessData);
        Map<String, Object> uniBssHead = KiteMapUtils.getValue(respMap, "UNI_BSS_HEAD");
        if (!KiteStringUtils.equals(KiteMapUtils.getString(uniBssHead, "RESP_CODE"), LocalInfConsts.RESP_SUCCESS)) {
            ErrorConsts.INF_INVOKE_EXCEPTION.throwOut(KiteMapUtils.getString(uniBssHead, "RESP_CODE"),
                KiteMapUtils.getString(uniBssHead, "RESP_DESC"));
        }
        Map<String, Object> uniBssBodyRespMap = KiteMapUtils.getValue(respMap, "UNI_BSS_BODY");
        Map<String, Object> specialProcessRspMap = KiteMapUtils.getValue(uniBssBodyRespMap, "SPECIAL_PROCESS_RSP");
        if (!LocalInfConsts.UNI_BSS_BODY_RESULT_SUCCESS.equals(KiteMapUtils.getString(specialProcessRspMap, "status"))) {
            return ErrorConsts.INF_INVOKE_EXCEPTION.getResult(KiteMapUtils.getString(specialProcessRspMap, "status"),
                KiteMapUtils.getString(specialProcessRspMap, "message"));
        }
        return ErrorConsts.SUCCESS.getResult("订单操作成功");
    }

    @KiteTransactional
    @ApiOperation(value = "手工起租", notes = "用于手工起租场景")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例标识", required = false)
    })
    @PostMapping("/startRent")
    public DataResult<String> startRent(String sceneInstId) {
        DataResult result = null;
        try {
            if (!KiteStringUtils.isEmpty(sceneInstId)) {
                KiteWebContext.getContext().setCurrentSceneInstId(sceneInstId);
            }

            String loadingTariffPlanFlag = querySceneInstService.getExtParameterValue(sceneInstId, "loadingTariffPlanFlag");
            if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_T)) {
                return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端仍在还原场景信息，请稍候...");
            }
            else if (KiteStringUtils.equals(loadingTariffPlanFlag, KeyConsts.IFTRUE_F)) {
                return ErrorConsts.BUSI_COMMON_ERROR.getResult("-1", "服务端异步处理场景信息失败，请重新进入页面...");
            }
            String worksheetId = querySceneInstService.getExtParameterValue(sceneInstId, "worksheetId");
            String taskCode = querySceneInstService.getExtParameterValue(sceneInstId, "taskCode");
            String taskId = querySceneInstService.getExtParameterValue(sceneInstId, "taskId");
            String orderId = querySceneInstService.getExtParameterValue(sceneInstId, "outOrderId");
            String dealResult = "DEAL_SUCCESS";
            // 获取所有子单，如果没有子单，返回当前工单
            List<Map<String, Object>> mergeOrders = infServiceBus.queryWorkSheetsMerge(orderId, worksheetId);
            if (KiteListUtils.isEmpty(mergeOrders)) {
                ErrorConsts.INF_INVOKE_EXCEPTION.throwOut("获取所有子单数据为空");
            }
            Map<String, Object> updateData = new HashMap<>();
            this.packageFlowData(sceneInstId, updateData, orderId, taskId, taskCode);
            Map order = new HashMap();
//            if (taskCode.startsWith("OrderStartRent")) {
//                KiteAttr startRentDate = querySceneInstService.getCommonAttr(sceneInstId, "REC_10057");
//                order.put("startRentDate", startRentDate.getValue() + " 00:00:00");
//            }
//            else if (taskCode.startsWith("OrderStopRent")) {
//                KiteAttr stopRentDate = querySceneInstService.getCommonAttr(sceneInstId, "REC10033");
//                order.put("stopRentDate", stopRentDate.getValue() + " 23:59:59");
//            }
            updateData.put("goods", Lists.newArrayList());
            updateData.put("order", order);

            for (Map<String, Object> orderInfo : mergeOrders) {
                result = orderSignService.overOrderTaskMerge(sceneInstId, ContextUtil.getUserId().toString(),
                    KiteMapUtils.getString(orderInfo, "orderId"), KiteMapUtils.getString(orderInfo, "flowId"), taskCode, taskId,
                    dealResult, null, (CuccContextCustDTO) KiteWebContext.getContext().getCust(), updateData);
                if (!KeyConsts.SUCCESS_0.equals(result.getResultCode())) {
                    return result;
                }
            }
        } catch (BssException ex) {
            result = ErrorConsts.BUSI_COMMON_ERROR.getResult(ex.getFailCode(), ex.getFailMsg());
        }
        return result;
    }

    private void packageFlowData(String sceneInstId, Map<String, Object> updateData, String orderId, String taskId, String taskCode) {
        List flowData = new ArrayList();
        Map flowDataMap = new HashMap();
        flowData.add(flowDataMap);
        updateData.put("flowData", flowData);
        List flowValueList = new ArrayList();
        String[] fieldNames;
        String dateStr = KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14);
        String code = RandomStringUtils.randomNumeric(3);
        if (taskCode.startsWith("OrderStartRent")) {
            fieldNames = new String[]{"REC_10057", "REC_10046", "REC_20004", "REC_20005"};
            for (int i = 0; i < fieldNames.length; i++) {
                Map flowValueMap = new HashMap();
                String fieldName = fieldNames[i];
                KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, fieldName);
                if (KiteObjectUtils.isEmpty(kiteAttr)) {
                    continue;
                }
                //起租时间带上时分秒
                if ("REC_10057".equals(fieldName)) {
                    kiteAttr.setValue(kiteAttr.getValue());
                }
                flowValueMap.put("code", fieldName);
                flowValueMap.put("grouptype", "0");
                flowValueMap.put("groupId", dateStr.concat(code));
                flowValueMap.put("value", kiteAttr.getValue());
                //附件处理
                if ("REC_10046".equals(kiteAttr.getFieldName()) && !KiteStringUtils.isEmpty(kiteAttr.getValue())) {
                    JSONArray arrs = JSONArray.parseArray(kiteAttr.getValue());
                    JSONObject obj = (JSONObject) arrs.get(0);
                    String url = (String) obj.get("attachmentUrl");
                    flowValueMap.put("value", url);
                }
                flowValueList.add(flowValueMap);
            }
            flowDataMap.put("flowKey", "OrderStartRent");
        }
        else if (taskCode.startsWith("OrderStopRent")) {
            fieldNames = new String[]{"REC10033", "REC_10046", "REC10034"};
            for (int i = 0; i < fieldNames.length; i++) {
                Map flowValueMap = new HashMap();
                String fieldName = fieldNames[i];
                KiteAttr kiteAttr = querySceneInstService.getCommonAttr(sceneInstId, fieldName);
                if (KiteObjectUtils.isEmpty(kiteAttr)) {
                    continue;
                }
                //止租时间带上时分秒
                if ("REC10033".equals(fieldName)) {
                    kiteAttr.setValue(kiteAttr.getValue() + " 23:59:59");
                }
                flowValueMap.put("code", fieldName);
                flowValueMap.put("grouptype", "0");
                flowValueMap.put("groupId", dateStr.concat(code));
                flowValueMap.put("value", kiteAttr.getValue());
                //附件处理
                if ("REC_10046".equals(kiteAttr.getFieldName()) && !KiteStringUtils.isEmpty(kiteAttr.getValue())) {
                    JSONArray arrs = JSONArray.parseArray(kiteAttr.getValue());
                    JSONObject obj = (JSONObject) arrs.get(0);
                    String url = (String) obj.get("attachmentUrl");
                    flowValueMap.put("value", url);
                }
                flowValueList.add(flowValueMap);
            }
            flowDataMap.put("flowKey", "OrderStopRent");
        }

        flowDataMap.put("flowValue", JSONArray.toJSONString(flowValueList));
        flowDataMap.put("flowDataId", "");
        flowDataMap.put("orderId", orderId);
        flowDataMap.put("taskId", taskId);
    }

    //特殊流程 处理退单的附件和备注
    //封装附件
    private String dealAttachements(String SceneInstId) {
        List<KiteAttr> commAttrs = querySceneInstService
            .listCommonAttrs(SceneInstId, KeyConsts.COMMON_OBJECT_TYPE);
        List<KiteAttr> attachements = commAttrs.stream()
            .filter((attr) -> LocalKeyConsts.COMMON_ATTR_KEY_ATTACHMENT.equals(attr.getFieldName()))
            .collect(Collectors.toList());
        Map attachementsMap = new HashMap();
        if (!KiteListUtils.isEmpty(attachements) && !KiteStringUtils.equals(attachements.get(0).getValue(), "[]")) {
            KiteAttr kiteAttr = attachements.get(0);
            List attachments = new ArrayList<>();
            String jsonStr = kiteAttr.getValue();
            if (!KiteStringUtils.isEmpty(jsonStr)) {
                JSONArray arrs = JSONArray.parseArray(jsonStr);
                for (int i = 0; i < arrs.size(); i++) {
                    JSONObject obj = arrs.getJSONObject(i);
                    attachementsMap.put("ATTACHMENTS_TYPE",obj.getString("fileType").replace("ATTACHMENTS_TYPE_", ""));
                    attachementsMap.put("fileName",obj.getString("attachmentUrl"));
                    attachementsMap.put("showSize","");
                    attachementsMap.put("backFileName",obj.getString("fileTypeName"));
                    String name = obj.getString("fileName");
                    if (KiteStringUtils.isNotEmpty(obj.getString("type"))) {
                        name = KiteStringUtils.join(obj.getString("fileName"), SymbolConsts.PERIOD, obj.getString("type"));
                    }
                    attachementsMap.put("backFileName",name);
                    // 文件类型图标:icon- fileType,
                    attachementsMap.put("fileTypeIcon","");
                    attachementsMap.put("uploadTime",obj.getString("createDate"));
                    attachementsMap.put("fileType",obj.getString("type"));
                    attachments.add(JSONObject.toJSONString(attachementsMap));
                }
            }
            if(!KiteObjectUtils.isEmpty(attachments)){
                return attachments.toString();
            }
        }
        return null;
    }

    @KiteTransactional
    @ApiOperation(value = "趸交订单缴费按钮", notes = "判断是否需要展示趸交订单缴费按钮")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例标识", required = true)
    })
    @GetMapping("/payOneOffFeeButton")
    public DataResult<Map> showPayButton(String sceneInstId) {
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        Map result = new HashMap();
        result.put("payNow", "false");
        result.put("payLater", "false");
        List<KiteInst> oneOffFees = CuccPosServiceUtils.queryOneOffFees(sceneInstId)
            .stream().filter(additionalOffer -> ActionType.A.name().equals(additionalOffer.getActionType().name()))
            .collect(Collectors.toList());
        if (CuccPosServiceUtils.showAndEditOneOffAddionalOffer(sceneInstId) && KiteListUtils.isNotEmpty(oneOffFees)) {
            result.put("payNow", "true");
            if (!"17".equals(sceneInst.getProvinceNbr())) {
                result.put("payLater", "true");
            }
        }
        return ErrorConsts.SUCCESS.getResult(result);
    }
    private List<KitePosAttrDTO> attrAZ(String sceneInstId){
        // A端要求完成时间/PE端要求完成时间
        KiteAttr aFinishAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.MV_REPLACE_A);
        if(null==aFinishAttr){
            aFinishAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.REPLACE_A);
        }
        // Z端要求完成时间/CE端要求完成时间
        KiteAttr zFinishAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.MV_REPLACE_Z);
        if(null==zFinishAttr){
            zFinishAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.REPLACE_Z);
        }
        List<KiteAttr> attrAZ = new ArrayList<>();
        List<KitePosAttrDTO> attrsAZ = new ArrayList<>();
        if (Objects.nonNull(aFinishAttr) && KiteStringUtils.isNotEmpty(aFinishAttr.getValue())) {
            aFinishAttr.setValue(aFinishAttr.getValue().substring(0, 10));
            aFinishAttr.setValueDesc(aFinishAttr.getValue().substring(0, 10));
            aFinishAttr.setFieldName(LocalKeyConsts.MV_REPLACE_A);
            attrAZ.add(aFinishAttr);
        }
        if (Objects.nonNull(zFinishAttr) && KiteStringUtils.isNotEmpty(zFinishAttr.getValue())) {
            zFinishAttr.setValue(zFinishAttr.getValue().substring(0, 10));
            zFinishAttr.setValueDesc(zFinishAttr.getValue().substring(0, 10));
            zFinishAttr.setFieldName(LocalKeyConsts.MV_REPLACE_Z);
            attrAZ.add(zFinishAttr);
        }
        if (KiteListUtils.isNotEmpty(attrAZ)) {
            attrAZ.forEach(attrList -> {
                KitePosAttrDTO attr = new KitePosAttrDTO();
                attr.setCode(attrList.getFieldName());
                attr.setType("STRING");
                attr.setStartDate(KiteDateUtils.formatDate(new Date(), KiteDateUtils.DATE_TIME_FORMAT_14));
                attr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
                attr.setValue(attrList.getValue());
                attrsAZ.add(attr);
            });
        }
        return attrsAZ;
    }
}
